package com.taotao.asyn;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.LinkedBlockingDeque;


@Component
@Slf4j
public class AsynSendWechatTemplate {
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 缓存报错内容
     */
    private static LinkedBlockingDeque<JSONObject> errorMsg = new LinkedBlockingDeque<JSONObject>();

    public AsynSendWechatTemplate() {
        new ThreadAsynSendWechatTemplate().start();
    }

    public void add(JSONObject data) {
        errorMsg.offer(data);
    }

    /**
     * 相同的错误在一分内 只应该提醒一次。
     */
    class ThreadAsynSendWechatTemplate extends Thread {
        @Override
        public void run() {
            log.info("<异步调用微信服务接口线程启动...>");
            while (true) {
                JSONObject data = errorMsg.poll();
                if (data != null) {
                    // 调用微信服务接口
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                    HttpEntity<String> formEntity = new HttpEntity<String>(data.toString(), headers);
                    String result = restTemplate.postForEntity("http://localhost:8088/sendWechatTemplateError", formEntity, String.class).getBody();
                    log.info("result:" + result);
                }
                try {
                    // cpu飙高---
                    Thread.sleep(100);
                } catch (Exception e) {

                }
            }
        }
    }


}
